package org.tlipoca.smsteamstore.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mongodb.client.MongoClient;
import lombok.extern.slf4j.Slf4j;
import org.genntii.smcommon.constant.ExceptionConstant;
import org.genntii.smcommon.constant.ExceptionStatusCodeConstant;
import org.genntii.smcommon.constant.SteamApiURLConstant;
import org.genntii.smcommon.exception.SteamDetailNotFoundException;
import org.genntii.smcommon.utils.HttpClientUtil;
import org.genntii.smdomain.entity.SteamAppDetail;
import org.genntii.smdomain.entity.SteamStore;
import org.tlipoca.smsteamstore.mapper.SteamStoreMapper;
import org.tlipoca.smsteamstore.service.SteamStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Service
public class SteamStoreServiceImpl extends ServiceImpl<SteamStoreMapper, SteamStore> implements SteamStoreService {

    @Autowired
    public SteamStoreMapper steamStoreMapper;

    @Autowired
    public MongoTemplate mongoTemplate;
    @Autowired
    private MongoClient mongo;

    @Override
    public SteamAppDetail getSteamStoreByIdService(Integer appid) {

        Map<String, Object> map = Map.of("appdetails", appid);
        JSONObject result = null;
        //TODO 这个链接大抵是挂了
        try {
            result = (JSONObject) JSON.parseObject(HttpClientUtil.doGetWithRetry(SteamApiURLConstant.GET_APP_DETAIL, map, 100)).get(appid.toString());
        } catch (Exception e) {
            log.info("更新AppDetail失败");
            return mongoTemplate.findOne(new Query(Criteria.where("steam_appid").is(appid)), SteamAppDetail.class);
        }

        if (!(Boolean) result.get("success")) {
            log.info("Steam返回AppDetail失败");
            throw new SteamDetailNotFoundException(ExceptionConstant.STEAM_DETAIL_NOT_FOUND_EXCEPTION);
        }

        SteamAppDetail steamAppDetail = JSON.toJavaObject((JSONObject) result.get("data"), SteamAppDetail.class);

        SteamStore steamStore = SteamStore.builder()
                .appid(steamAppDetail.getSteam_appid())
                .name(steamAppDetail.getName())
                .shortDescription(steamAppDetail.getShort_description())
                .detailDescription(steamAppDetail.getDetailed_description())
                .isDlc(steamAppDetail.getType().equals("dlc"))
                .headerImage(steamAppDetail.getHeader_image())
                .capsuleImage(steamAppDetail.getCapsule_image())
                .requiredAge(steamAppDetail.getRequired_age())
                .isFree(steamAppDetail.getIs_free())
                .build();

        log.info("更新Mysql...");
        // 游戏详情更新到Mysql
        steamStoreMapper.update(steamStore, new QueryWrapper<SteamStore>().eq("appid", steamStore.getAppid()));

        // 更新Mongodb
        log.info("更新Mongodb");
        Iterator<String> iterator = result.keySet().iterator();
        Update update = new Update();
        while (iterator.hasNext()) {
            String key = iterator.next();
            update.set(key, result.get(key));
        }

        mongoTemplate.upsert(new Query(Criteria.where("steam_appid").is(appid)), update, SteamAppDetail.class);

        return steamAppDetail;
    }

    @Override
    public ArrayList<Integer> getSteamStoreAppidListService() {
        return steamStoreMapper.selectAppidList();
    }

    @Override
    public Boolean steamStoreExistsService(Integer appid) {
        return steamStoreMapper.exists(new QueryWrapper<SteamStore>().eq("appid", appid));
    }

    @Override
    public ArrayList<SteamStore> getSteamAppListBatchByIds(ArrayList<Integer> ids) {
        ArrayList<SteamStore> steamStores = steamStoreMapper.getSteamStoreListByIds(ids);
        return steamStores;
    }
}
